package com.bc.web.controller.admin;

import com.bc.web.config.R;
import com.bc.web.model.RiskRule;
import com.fs.common.extend.FSController;
import com.fs.common.util.FSDate;
import com.fs.common.util.FSJedis;
import com.fs.common.util.FSJson;
import com.fs.common.util.FSMD5;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;

public class RiskRuleController extends FSController{

	public void search(){
		Page<RiskRule> pageResult = RiskRule.dao.search(super.getSearchCondition());
		setPageResultToRequest("items", pageResult);
		render("basedata/riskRuleList.html");
	}
	
	public void addPage(){
		render("basedata/riskRuleAdd.html");
	}
	
	public void updatePage(){
		RiskRule risk = RiskRule.dao.findById(getPara("id"));
		risk.setSumLimit(risk.getSumLimit()  / 100);
		risk.setDayLimit(risk.getDayLimit() / 100);
		risk.setPayTypeDayLimit(risk.getPayTypeDayLimit() / 100);
		risk.setSingleLimit(risk.getSingleLimit() / 100);
		setAttr("risk", risk);
		render("basedata/riskRuleUpdate.html");
	}
	
	@Before(Tx.class)
	public void add(){
		RiskRule risk = getModel(RiskRule.class,true);
		if(RiskRule.dao.selectByName(risk.getName()) != null) {
			renderFail("名称重复");
		}else {
			risk.setSumLimit(risk.getSumLimit()  * 100);
			risk.setDayLimit(risk.getDayLimit() * 100);
			risk.setPayTypeDayLimit(risk.getPayTypeDayLimit() * 100);
			risk.setSingleLimit(risk.getSingleLimit() * 100);
			StringBuffer sb = new StringBuffer();
			sb.append("sumLimit" + risk.getSumLimit());
			sb.append("dayLimit" + risk.getDayLimit());
			sb.append("payTypeDayLimit" + risk.getPayTypeDayLimit());
			sb.append("singleLimit" + risk.getSingleLimit());
			sb.append("tradeStartTime" + risk.getTradeStartTime());
			sb.append("tradeEndTime" + risk.getTradeEndTime());
			risk.setMd5(FSMD5.codeFor(sb.toString()));
			risk.setUpdateTime(FSDate.getDateTime());
			risk.save();
			if (R.IS_REDIS) {
				FSJedis.update(R.RK_RISK, risk.getId().toString(), FSJson.toString(risk));
			}
			renderSuccess();
		}
	}
	
	@Before(Tx.class)
	public void update(){
		RiskRule risk = getModel(RiskRule.class);
		risk.setSumLimit(risk.getSumLimit()  * 100);
		risk.setDayLimit(risk.getDayLimit() * 100);
		risk.setPayTypeDayLimit(risk.getPayTypeDayLimit() * 100);
		risk.setSingleLimit(risk.getSingleLimit() * 100);
		risk.setUpdateTime(FSDate.getDateTime());
		risk.update();
		if (R.IS_REDIS) {
			FSJedis.update(R.RK_RISK, risk.getId().toString(), FSJson.toString(risk));
		}
		renderSuccess();
	}
	
	@Before(Tx.class)
	public void delete(){
		RiskRule r = RiskRule.dao.findById(getPara("id"));
		RiskRule.dao.deleteById(r.getId());
		if (R.IS_REDIS) {
			FSJedis.remove(R.RK_RISK, r.getId().toString());
		}
		renderSuccess(false);
	}
	
}
